package com.github.hwangrq.myrpc.consumer.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;

/**
 * @author hwangrq
 * 客户端处理类 同步
 * 1.发送消息 - 线程等待
 * 2.接收消息 - 线程唤醒
 */
@ChannelHandler.Sharable
public class RpcClientHandler extends SimpleChannelInboundHandler<String>
        implements Callable<Object> {

    private ChannelHandlerContext context;

    /** 客户端发送消息 */
    private String requestMsg;

    /** 服务端消息 */
    private String responseMsg;

    public void setRequestMsg(String requestMsg) {
        this.requestMsg = requestMsg;
    }

    @Override
    public synchronized void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
    }

    @Override
    protected synchronized void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        responseMsg = msg;
        notify();
    }

    @Override
    public synchronized Object call() throws Exception {
        context.writeAndFlush(requestMsg);
        wait();
        return responseMsg;
    }
}
